package com.controller;

import com.pojo.User;
import com.service.LoginService;
import com.utils.Md5Utils;
import com.utils.RandomCodeServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/login/*")
public class LoginServlet extends BaseServlet{

    public void loginU(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String s = Md5Utils.MD5Encode(userPassword, "utf-8", false);
        String r = req.getParameter("randomCode");
        User user = new User(userName,s);
        Object randomcode = req.getSession().getAttribute("RANDOMCODE_IN_SESSION");
        LoginService ls = new LoginService();
        boolean b = ls.queryUser(user);
        if(!r.equals(randomcode)){
            req.getSession().setAttribute("msg","验证码错误");
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
        }else{
            if(b){
                req.getSession().setAttribute("LOGIN_NAME",user.getUserName());
//                System.out.println(req.getSession().getAttribute("LOGIN_NAME")+"登录成功名字");
                resp.sendRedirect(req.getContextPath()+"/jsp/frame.jsp");
            }else{
                req.getSession().setAttribute("msg","账号密码错误");
                resp.sendRedirect(req.getContextPath()+"/login.jsp");
            }
        }
    }

    public void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().removeAttribute("LOGIN_NAME");
        resp.sendRedirect(req.getContextPath()+"/login.jsp");
    }
}
